<template>
  <div>
    <a-input-search
      v-model="selectedOrderNos"
      :placeholder="placeholder"
      :disabled="disabled"
      readOnly
      @search="handleSearch">
      <a-button slot="enterButton" :disabled="disabled">选择</a-button>
    </a-input-search>
    <a-modal
      :title="title"
      :width="modalWidth"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel">
      
      <a-spin :spinning="confirmLoading">
        <!-- 查询区域 -->
        <div class="query-area">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="8" :sm="12">
                <a-form-item label="订单编号">
                  <a-input placeholder="请输入订单编号" v-model="queryParam.orderNo" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item label="客户名称">
                  <a-input placeholder="请输入客户名称" v-model="queryParam.customerName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item label="工程名称">
                  <a-input placeholder="请输入工程名称" v-model="queryParam.projectName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item label="订单状态">
                  <a-select placeholder="请选择订单状态" v-model="queryParam.status" allowClear>
                    <a-select-option :value="1">审核通过</a-select-option>
                    <a-select-option :value="2">已上传汇总单</a-select-option>
                    <a-select-option :value="3">已上传优化单</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        
        <!-- 表格区域 -->
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox' : 'radio'}"
          :customRow="customRowClick"
          :scroll="{ x: 1200 }"
          @change="handleTableChange">
          
          <!-- 金额格式化 -->
          <template slot="moneySlot" slot-scope="text">
            <span v-if="text !== undefined && text !== null">{{ Number(text).toLocaleString('zh-CN', { style: 'currency', currency: 'CNY', minimumFractionDigits: 2 }) }}</span>
            <span v-else>¥0.00</span>
          </template>
          
          <!-- 状态列 -->
          <template slot="statusSlot" slot-scope="text">
            <a-tag :color="getStatusColor(text)">
              {{ getStatusText(text) }}
            </a-tag>
          </template>
        </a-table>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
  import { getAction } from '@/api/manage'
  
  export default {
    name: 'JSelectProductionOrderModal',
    props: {
      value: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: '请选择订单'
      },
      disabled: {
        type: Boolean,
        default: false
      },
      modalWidth: {
        type: Number,
        default: 1000
      },
      multiple: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '选择订单'
      },
      showYuLiaoOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: [Number, String],
        default: null
      }
    },
    data() {
      return {
        visible: false,
        confirmLoading: false,
        selectedRowKeys: [],
        selectedOrderIds: [], // 保存选择的订单ID
        selectedOrderNos: '', // 保存选择的订单编号
        selectedOrders: [], // 保存选择的订单信息
        
        // 查询条件
        queryParam: {
          orderNo: '',
          customerName: '',
          projectName: '',
          status: undefined
        },
        
        // 数据源
        dataSource: [],
        
        // 表格列
        columns: [
          {
            title: '订单编号',
            dataIndex: 'orderNo',
            width: 120,
            align: "center",
            ellipsis: true
          },
          {
            title: '客户名称',
            dataIndex: 'customerName',
            width: 150,
            align: "center",
            ellipsis: true
          },
          {
            title: '工程名称',
            dataIndex: 'projectName',
            width: 150,
            align: "center",
            ellipsis: true
          },
          {
            title: '下单日期',
            dataIndex: 'orderDate',
            width: 100,
            align: "center"
          },
          {
            title: '交付日期',
            dataIndex: 'deliveryDate',
            width: 100,
            align: "center"
          },
          {
            title: '销售负责人',
            dataIndex: 'salesPersonName',
            width: 100,
            align: "center"
          },
          {
            title: '销售额',
            dataIndex: 'totalAmount',
            width: 120,
            align: "right",
            scopedSlots: { customRender: 'moneySlot' }
          },
          {
            title: '状态',
            dataIndex: 'status',
            width: 100,
            align: "center",
            scopedSlots: { customRender: 'statusSlot' }
          }
        ],
        
        // 分页参数
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        
        loading: false,
        url: {
          list: '/oms/productSalesOrder/approvedList',
          yuLiaoList: '/oms/productSalesOrder/getOrderListWithoutYuLiaoRuku',
          getOrdersByIds: '/oms/productSalesOrder/getOrdersByIds'
        }
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(val) {
          if (val) {
            this.initSelectedOrders(val);
          } else {
            this.selectedOrderIds = [];
            this.selectedOrderNos = '';
            this.selectedOrders = [];
            this.selectedRowKeys = [];
          }
        }
      }
    },
    created() {
      // 如果传入了status参数，设置默认查询条件
      if (this.status !== null) {
        this.queryParam.status = this.status;
      }
      this.searchReset();
    },
    methods: {
      // 获取状态文本
      getStatusText(status) {
        switch (parseInt(status)) {
          case 0: return '待审核';
          case 1: return '审核通过';
          case 2: return '已上传汇总单';
          case 3: return '已上传优化单';
          case 9: return '已取消';
          default: return '未知状态';
        }
      },
      
      // 获取状态颜色
      getStatusColor(status) {
        switch (parseInt(status)) {
          case 0: return 'orange';
          case 1: return 'blue';
          case 2: return 'cyan';
          case 3: return 'green';
          case 9: return 'red';
          default: return 'default';
        }
      },
      
      // 自定义行点击事件
      customRowClick(record) {
        return {
          onClick: () => {
            this.handleRowClick(record);
          }
        };
      },
      
      // 初始化已选择的订单信息
      initSelectedOrders(selectedIds) {
        if (!selectedIds) return;
        
        this.loading = true;
        let params = { ids: selectedIds };
        
        getAction(this.url.getOrdersByIds, params).then(res => {
          if (res.success) {
            this.selectedOrders = res.result || [];
            this.selectedOrderIds = this.selectedOrders.map(item => item.id);
            this.selectedOrderNos = this.selectedOrders.map(item => item.orderNo).join(',');
            this.selectedRowKeys = this.selectedOrderIds;
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 打开选择框
      handleSearch() {
        if (this.disabled) return;
        
        this.visible = true;
        this.loadData(1);
      },
      
      // 加载数据
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        
        const params = this.getQueryParams();
        this.loading = true;
        
        // 根据是否只显示未生成余料入库单的订单来选择接口
        const url = this.showYuLiaoOnly ? this.url.yuLiaoList : this.url.list;
        
        getAction(url, params).then(res => {
          if (res.success) {
            this.dataSource = res.result.records || [];
            this.ipagination.total = res.result.total || 0;
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 获取查询参数
      getQueryParams() {
        const param = Object.assign({}, this.queryParam);
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return param;
      },
      
      // 选择改变
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        
        if (!this.multiple) {
          this.selectedOrders = selectedRows;
        } else {
          // 保持已经选择的和当前页面选择的
          const selectedIds = selectedRows.map(row => row.id);
          this.selectedOrders = this.selectedOrders.filter(item => {
            return selectedIds.includes(item.id) || !this.dataSource.map(row => row.id).includes(item.id);
          });
          
          // 添加当前页面新选择的
          selectedRows.forEach(row => {
            const exist = this.selectedOrders.some(item => item.id === row.id);
            if (!exist) {
              this.selectedOrders.push(row);
            }
          });
        }
      },
      
      // 查询按钮
      searchQuery() {
        this.loadData(1);
      },
      
      // 重置按钮
      searchReset() {
        this.queryParam = {
          orderNo: '',
          customerName: '',
          projectName: '',
          status: this.status || undefined
        };
        this.loadData(1);
      },
      
      // 表格分页、排序、筛选变化
      handleTableChange(pagination, filters, sorter) {
        this.ipagination.current = pagination.current;
        this.ipagination.pageSize = pagination.pageSize;
        this.loadData();
      },
      
      // 处理行点击事件
      handleRowClick(record) {
        // 获取当前行的key
        const rowKey = record.id;
        
        // 根据是否多选处理不同的逻辑
        if (!this.multiple) {
          // 单选模式：直接设置当前行为选中状态
          this.selectedRowKeys = [rowKey];
          this.selectedOrders = [record];
        } else {
          // 多选模式：切换选中状态
          const index = this.selectedRowKeys.indexOf(rowKey);
          if (index === -1) {
            // 如果未选中，则添加到选中列表
            this.selectedRowKeys.push(rowKey);
            
            // 检查记录是否已存在于selectedOrders中
            const exist = this.selectedOrders.some(item => item.id === record.id);
            if (!exist) {
              this.selectedOrders.push(record);
            }
          } else {
            // 如果已选中，则从选中列表移除
            this.selectedRowKeys.splice(index, 1);
            
            // 从selectedOrders中移除
            const orderIndex = this.selectedOrders.findIndex(item => item.id === record.id);
            if (orderIndex !== -1) {
              this.selectedOrders.splice(orderIndex, 1);
            }
          }
        }
      },
      
      // 确定按钮
      handleOk() {
        this.selectedOrderIds = this.selectedOrders.map(item => item.id);
        this.selectedOrderNos = this.selectedOrders.map(item => item.orderNo).join(',');
        
        this.$emit('input', this.selectedOrderIds.join(','));
        this.$emit('change', this.selectedOrderIds.join(','), this.selectedOrders);
        
        this.handleCancel();
      },
      
      // 取消按钮
      handleCancel() {
        this.visible = false;
      }
    }
  }
</script>

<style scoped>
  .query-area {
    margin-bottom: 16px;
  }
  
  /* 添加鼠标悬停样式，提升用户体验 */
  :deep(.ant-table-tbody > tr) {
    cursor: pointer;
  }
  
  :deep(.ant-table-tbody > tr:hover) {
    background-color: #e6f7ff;
  }
  
  /* 表格样式优化 */
  .ant-table-bordered .ant-table-thead > tr > th,
  .ant-table-bordered .ant-table-tbody > tr > td {
    padding: 12px 8px;
  }
  
  /* 金额列右对齐 */
  .ant-table-tbody > tr > td.ant-table-column-money {
    text-align: right !important;
  }
</style> 